package com.bff.gaia.streaming.api.mo.gaia.network;

import com.bff.gaia.streaming.api.mo.gaia.io.basiccoder.DoubleCoder;
import com.bff.gaia.streaming.api.mo.gaia.network.server.Server;

import java.util.Hashtable;

public class Hash {
	Server server = null;

	private Hashtable<String, DoubleCoder> hashtable = new Hashtable();

	public Hash(Server server) {
		this.server = server;
	}

	public void set(String key, Double val) {
		this.setMax(key, val);
		this.setMin(key, val);
	}

	private void set(String key, Double val, boolean minormax) {
		DoubleCoder dc = new DoubleCoder(val);
		DoubleCoder old = (DoubleCoder)this.hashtable.get(key);
		if (old == null) {
			this.hashtable.put(key, dc);
		} else {
			Double oval = old.getDouble();
			if (oval == null) {
				this.hashtable.put(key, dc);
				this.server.log((minormax ? "min" : "max") + " changed from " + oval + " to " + dc.getDouble());
			} else if (val != null && oval.compareTo(val) < 0 ^ minormax) {
				this.server.log((minormax ? "min" : "max") + " changed from " + oval + " to " + dc.getDouble());
				this.hashtable.put(key, dc);
			}
		}

	}

	private void setMin(String key, Double val) {
		String minkey = key + ".min";
		this.set(minkey, val, true);
	}

	private void setMax(String key, Double val) {
		String maxkey = key + ".max";
		this.set(maxkey, val, false);
	}

	public Double getMax(String key) {
		String maxkey = key + ".max";
		return this.get(maxkey);
	}

	public Double getMin(String key) {
		String minkey = key + ".min";
		return this.get(minkey);
	}

	private Double get(String key) {
		DoubleCoder val = (DoubleCoder)this.hashtable.get(key);
		if (val == null) {
			return null;
		} else {
			Double v = val.getDouble();
			return v;
		}
	}

	public void reset(String key) {
		this.hashtable.remove(key + ".max");
		this.hashtable.remove(key + ".min");
	}

	public static void main(String[] args) {
	}
}
